<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\plugin;

use app\common\plugin\MainApiService;
use support\Request;
use support\Response;

/**
 * 插件市场控制器
 * 对接main项目的API接口
 */
class Market extends Base
{
    private $mainApi;

    public function __construct()
    {
        parent::__construct();
        $this->mainApi = new MainApiService();
    }

    /**
     * 获取远程应用市场 应用列表
     */
    public function getPlugins()
    {
        try {
            $request = request();
            $params  = [
                'search'      => $request->get('search', ''),
                'category'    => $request->get('category', ''),
                'category_id' => $request->get('category_id', ''),
                'keyword'     => $request->get('keyword', ''),
                'type'        => $request->get('type', ''), // plugin, template
                'price_type'  => $request->get('price_type', ''), // free, paid
                'sort'        => $request->get('sort', 'latest'),
                'limit'       => $request->get('limit', 20),
                'page'        => $request->get('page', 1),
            ];

            // 统一从后端获取token（如果已登录）
            $token = $this->getUserToken();
            if (!empty($token)) {
                $params['token'] = $token;
            }

            // 过滤空参数
            $params = array_filter($params, function ($value) {
                return $value !== '' && $value !== null;
            });

            $data = $this->mainApi->getPlugins($params);
            return $this->success('获取成功', $data);
        } catch (\Exception $e) {
            return $this->error('获取插件列表失败: ' . $e->getMessage());
        }
    }

    /**
     * 跳转到注册页面
     */
    public function register()
    {
        return redirect($this->getMainApiUrl('/register'));
    }

    /**
     * 跳转到插件详情
     */
    public function detail()
    {
        $request = request();
        $id      = $request->get('id');
        return redirect($this->getMainApiUrl('/plugins/show/') . $id);
    }

    /**
     * 创建支付订单（代理到API市场）
     */
    public function createPaymentOrder()
    {
        try {
            $request       = request();
            $itemType      = $request->post('item_type');
            $itemId        = $request->post('item_id');
            $paymentMethod = $request->post('payment_method');

            // 验证参数
            if (empty($itemType) || empty($itemId) || empty($paymentMethod)) {
                return $this->error('参数不完整');
            }

            if (!in_array($itemType, ['plugin', 'template'])) {
                return $this->error('商品类型无效');
            }

            if (!in_array($paymentMethod, ['alipay', 'wechat'])) {
                return $this->error('支付方式无效');
            }

            // 统一从后端获取token
            $token = $this->getUserToken();
            if (empty($token)) {
                return $this->error('请先登录', 401);
            }

            // 设置token并调用主API创建订单
            $this->mainApi->setToken($token);
            $response = $this->mainApi->createPaymentOrder([
                'item_type'      => $itemType,
                'item_id'        => (int) $itemId,
                'payment_method' => $paymentMethod
            ]);

            return $this->success('订单创建成功', $response);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 检查支付状态（代理到API市场）
     */
    public function checkPaymentStatus()
    {
        try {
            $request = request();
            $orderNo = $request->post('order_no');

            if (empty($orderNo)) {
                return $this->error('订单号不能为空');
            }

            // 统一从后端获取token
            $token = $this->getUserToken();
            if (empty($token)) {
                return $this->error('请先登录', 401);
            }

            // 设置token并调用主API检查支付状态
            $this->mainApi->setToken($token);
            $response = $this->mainApi->checkPaymentStatus([
                'order_no' => $orderNo
            ]);

            return $this->success('查询成功', $response);
        } catch (\Exception $e) {
            return $this->error('查询支付状态失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取插件详情
     */
    public function getPlugin()
    {
        try {
            $request = request();
            $id      = $request->get('id');
            if (!$id) {
                return $this->error('插件ID不能为空');
            }

            $data = $this->mainApi->getPlugin($id);

            return $this->success('获取成功', $data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取模板列表
     */
    public function getTemplates(Request $request): Response
    {
        try {
            $params = [
                'search'      => $request->get('search', ''),
                'category_id' => $request->get('category_id', ''),
                'sort'        => $request->get('sort', 'downloads'),
                'per_page'    => $request->get('per_page', 20),
                'page'        => $request->get('page', 1),
            ];

            // 过滤空参数
            $params = array_filter($params, function ($value) {
                return $value !== '' && $value !== null;
            });

            $data = $this->mainApi->getTemplates($params);

            return $this->success('获取成功', $data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取分类列表
     */
    public function getCategories(Request $request): Response
    {
        try {
            // 获取所有分类，不限制类型
            $data = $this->mainApi->getCategories();

            return $this->success('获取成功', $data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }



    /**
     * 获取用户模板
     */
    public function getUserTemplates(Request $request): Response
    {
        try {
            $token = $request->session()->get('main_api_token');
            if (!$token) {
                return $this->error('请先登录官网账户');
            }

            $this->mainApi->setToken($token);
            $data = $this->mainApi->getUserTemplates();

            return $this->success('获取成功', $data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 购买插件
     */
    public function purchasePlugin(Request $request): Response
    {
        try {
            $pluginId    = $request->post('plugin_id');
            $licenseType = $request->post('license_type', 'basic'); // basic, premium

            if (!$pluginId) {
                return $this->error('插件ID不能为空');
            }

            // 这里应该实现支付逻辑
            // 暂时直接返回成功
            return $this->success('购买成功', [
                'plugin_id'    => $pluginId,
                'license_type' => $licenseType,
                'order_id'     => 'ORDER_' . time(),
                'status'       => 'paid'
            ]);
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }


}
